package com.levi.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.levi.controller.order.OrderControllerApi;
import com.levi.controller.product.ProductControllerApi;
import com.levi.fallback.ProductcontrollerFallback;
import com.levi.pojo.Product;
import com.levi.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;

@RestController
@Slf4j
@RequestScope
public class ProductController implements ProductControllerApi {

    @Value("${config.info}")
    private String info;

    @Value("${server.port}")
    private String port;

    @Autowired
    private ProductService productService;

    @Override
    public Boolean save(String name,Integer stock) {
        Product product = new Product();
        product.setName(name);
        product.setStock(stock);
        productService.save(product);
        System.out.println("保存商品成功");
        return true;
    }

    @Override
    @Transactional
    public String decutProduct(Integer id, Integer count) {
        Product product = getProductById(id);
        Integer stock = product.getStock();
        if (stock < count) {
            throw new RuntimeException("库存不足");
        }
        product.setStock(stock - count);
        productService.updateById(product);
        int i = 1 / 0;
        return "success";
    }

    @Override
    public Product getProductById(Integer id) {
        Product product = productService.getById(id);
        if (product == null) {
            throw new RuntimeException("没有该商品");
        }
        return product;
    }


    @Override
    public String configInfo() {
        return info;
    }

    @Override
    public String gateway() {
        return "gateway   success" + port;
    }

    /**
     * value 限流的资源
     * blockHandler 只捕获BlockException异常
     * fallback     捕获Throwable
     * 为了方便实际开发中只定义 fallback就行
     * 可以把fallback方法都放到一个类里面，用 fallbackClass= 指定该类
     * @return
     */
    @Override
    @SentinelResource(value = "testSentinel",fallbackClass = ProductcontrollerFallback.class, fallback = "testSentinel_fallback")
    public String testSentinel() {
        return "testSentinel";
    }

    /**
     * 参数类型要一致，参数要多加一个BlockException
     * @param e
     * @return
     */
    public String testSentinel_blockHandler(BlockException e) {
        return "blockException: >>>"+e;
    }

}
